package com.yc.thread;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @program: gitee3_thread
 * @description: 线程池
 * @author: zy
 * @create: 2024-07-14 10:39
 */
public class Test5_pool {

    public static void main(String[] args) {
        /* 核心线程池的大小 */
        int corePoolSize = 3;
        /* 核心线程池的最大线程数 */
        int maxPoolSize = 5;
        /* 线程最大空闲时间 */
        long keepAliveTime = 10;
        /* 时间单位 */
        TimeUnit unit = TimeUnit.SECONDS;    //  enum枚举.  常量
        /* 阻塞队列 容量为2     最多允许放入两个 空闲任务 */
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(2);       //  同时最大任务量为  7   ->超过７个任务，则执行拒绝．
        /* 线程创建工厂 */
        ThreadFactory threadFactory = new NameTreadFactory();
        /* 线程池拒绝策略 */
        RejectedExecutionHandler handler = new MyIgnorePolicy();

        ThreadPoolExecutor executor = null;
        try {
            /* 推荐的创建线程池的方式 */
            /* 不推荐使用现成的API创建线程池 */
            executor = new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);

            /* 预启动所有核心线程  提升效率 */
            executor.prestartAllCoreThreads();
            /* 任务数量 */
            int count = 10;
            for (int i = 1; i <= count; i++) {
                Task task = new Task(   String.valueOf(i)   );

                executor.submit(task);   //线程池中最多同时执行５个任务＋２个队列　　提交任务到线程池    还有３个任务无法执行．

            }
        } finally {
            assert executor != null;           //断言，可开关   -ea  -da
            executor.shutdown();
        }

    }

    /**
     * 线程工厂
     */
    static class NameTreadFactory implements ThreadFactory {
        /* 线程id    AtomicInteger 原子类　　　原子整型类 */
        private final AtomicInteger threadId = new AtomicInteger(1);

        @Override
        public Thread newThread(Runnable runnable) {
            Thread t = new Thread(runnable, "线程-" + threadId.getAndIncrement()); //  i++　　　=>　ｉ　　Ｉ＋１　　　＝＞　赋值
            System.out.println(t.getName() + " 已经被创建");
            return t;
        }
    }

    /**
     * 线程池拒绝策略
     */
    public static class MyIgnorePolicy implements RejectedExecutionHandler {
        @Override                   //被拒绝的任务             线程池对象.
        public void rejectedExecution(Runnable runnable, ThreadPoolExecutor e) {
            doLog(runnable, e);
        }
        private void doLog(Runnable runnable, ThreadPoolExecutor e) {
            // 可做日志记录等。
            System.err.println(   "线程池:"+e.toString() + runnable.toString() + " 被拒绝执行");
        }
    }



    //任务类
    static class Task implements Runnable{
        private String name;
        public Task(String name) {
            this.name = name;
        }
        @Override
        public void run() {
            try {
                System.out.println(this.toString() + " is running!");
                //让任务执行慢点。
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        @Override
        public String toString() {
            return "RunnableTask [name=" + name + "]";
        }
    }
}
